package org.csu.mypetstore.web.servlet;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "NewAccountServlet", value = "/NewAccountServlet")
public class NewAccountServlet extends HttpServlet {
    private static String SIGN_ON="/WEB-INF/jsp/account/SignonForm.jsp";
    private static String NEW_ACCOUNT="/WEB-INF/jsp/account/NewAccountForm.jsp";
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        AccountService accountService=new AccountService();
        //System.out.println("aaaaaaaa");
        Account account=new Account();
        HttpSession session=request.getSession();
        account.setUsername(request.getParameter("username"));
        account.setPassword(request.getParameter("password"));
        account.setFirstName(request.getParameter("account.firstname"));
        account.setLastName(request.getParameter("account.lastname"));
        account.setEmail(request.getParameter("account.email"));
        account.setPhone(request.getParameter("account.phone"));
        account.setAddress1(request.getParameter("account.address1"));
        account.setAddress2(request.getParameter("account.address2"));
        account.setCity(request.getParameter("account.city"));
        account.setState(request.getParameter("account.state"));
        account.setZip(request.getParameter("account.zip"));
        account.setCountry(request.getParameter("account.country"));
//        account.setFavouriteCategoryId(request.getParameter());
        //下拉框的值无法获取
        if(account.getPassword().equals(request.getParameter("repeatedPassword")))
        {
            try {
                Account account1=accountService.getAccountByUsername(account.getUsername());
                if(account1==null)
                {
                    accountService.insertAccount(account);
                    request.getRequestDispatcher(SIGN_ON).forward(request,response);
                }
                else
                {
                    session.setAttribute("msg","该用户名已存在");
                    request.getRequestDispatcher(NEW_ACCOUNT).forward(request,response);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else
        {
            session.setAttribute("msg","两次密码不匹配");
            request.getRequestDispatcher(NEW_ACCOUNT).forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           doGet(request,response);
    }
}
